package com.zyj.concurrency;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchTest {

    private static final Integer SIZE = 10;
    private static final AtomicInteger counter = new AtomicInteger();
    private static final CountDownLatch startCount = new CountDownLatch(1);
    private static final CountDownLatch endCount = new CountDownLatch(SIZE);
    private static final ExecutorService exec = Executors.newFixedThreadPool(SIZE);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < SIZE; i++){
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        // 等待开始信号
                        startCount.await();
                        int num = counter.getAndIncrement();
                        TimeUnit.SECONDS.sleep(num);
                        System.out.println("第" + num + "号员工准备完毕。。。");
                    } catch(Exception e) {
                        e.printStackTrace();
                    } finally {
                        // 当前线程结束
                        endCount.countDown();
                    }
                }
            });
        }

        // 所有线程准备就绪
        System.out.println("开始准备。。。");
        startCount.countDown();

        // 等待所有线程完成
        endCount.await();
        System.out.println("各单位准备就绪。。。开始干活。。。");

        exec.shutdown();
    }
}
